<template>
  <div>
    <basic-container>
      <div>
        <avue-crud :option="option"
          ref="crud"
          v-model="form"
          :page="page"
          @on-load="getList"
          @size-change="sizeChange"
          @current-change="currentChange"
          :table-loading="listLoading"
          @refresh-change="handleRefreshChange"
          @row-update="update"
          @row-save="create"
          :before-open="handleOpenBefore"
          :data="list">
          <template slot-scope="scope" slot="menuLeft">
            <el-button type="primary"
              icon="el-icon-plus"
              @click.stop="handleAdd()">新增培训机构</el-button>
          </template>
          <template slot="cityName"
                    slot-scope="scope">
            <span>{{scope.row.city}}</span>
          </template>
          <template slot="deptId"
                    slot-scope="scope">
            {{scope.row.deptName}}
          </template>
          <template slot="menu" slot-scope="scope">
            <el-button
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row,scope.index)">编辑
            </el-button>
            <el-button 
                type="text"
                icon="el-icon-delete"
                @click="deletes(scope.row,scope.index)">删除
            </el-button>
          </template>
          <template slot="examinationDepartmentArrForm"
                    slot-scope="scope">
                  <el-checkbox-group v-model="examinationDepartmentArr">
                    <el-checkbox :label="item.value" v-for="(item,i) in examinationDepartmentOptions" :key="i">{{item.label}}</el-checkbox>
                  </el-checkbox-group>
          </template>
          <template slot="hospitalDepartmentArrForm" slot-scope="scope">
                  <el-checkbox-group v-model="hospitalDepartmentArr">
                    <el-checkbox :label="item.value" v-for="(item, i) in hospitalDepartmentOptions" :key="i">{{item.label}}</el-checkbox>
                  </el-checkbox-group>
          </template>
          <template slot="trainingBaseIdForm"
            slot-scope="scope">
            <avue-select v-model="form.trainingBaseId"
                multiple
                placeholder="请选择类型"
                :dic="OrganizationOptions"
                :props="roleProps"></avue-select>
          </template>
          <template slot="provinceForm"
            slot-scope="scope">
            <el-select v-model="form.province" 
            @change="provinceChange"
            placeholder="请选择省">
              <el-option
                v-for="item in regionOptionsP"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </template>
          <template slot="cityForm"
            slot-scope="scope">
            <el-select v-model="form.city" placeholder="请选择市">
              <el-option
                v-for="item in regionOptionsC"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </template>
        </avue-crud>
      </div>
      <div class="dash">
        <h3>学员报名注册状况</h3>
        <div class="dataCol">
          <div class="item">
            报名数
            <span>{{dashData.totalNum || 0}}</span>
          </div>
          <div class="item">
            注册完成数
            <span>{{dashData.registerNum || 0}}</span>
          </div>
          <div class="item">
            未注册完成数
            <span @click="dialogFormVisible=true">{{dashData.infoNotAddNum || 0}} <b>查看</b></span>
          </div>
        </div>
      </div>
      <h3>各省学员报名/注册状况</h3>
      <div class="banner-text">
        <div id="main" style="width: 100%;height: 400px;"></div>
        <span>
          <el-collapse v-model="activeNames">
            
          </el-collapse>
        </span>
      </div>
    </basic-container>
    <el-dialog
      :visible.sync="dialogFormVisible"
      title="查看"
      width="60%">
      <avue-crud
        ref="crudItem"
        :page="stuPage"
        :data="dataStuList"
        :option="stuOption"
        @size-change="stuSizeChange"
        @current-change="stuCurrentChange">
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <!-- <el-button type="primary" @click="dialogFormVisible = false">导出EXCEL</el-button -->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import echarts from "echarts";
// import {studentNum, provinceStudentNum} from "@/api/admin/dash";
import {tableOption} from '@/const/crud/admin/index';
// import { fetchList, putObj,deptOrganizationList, regionList, addObj} from "@/api/admin/organization";
import {fetchList as fetchStuList }  from '@/router/axios'

export default {
  name: "wel",
  data() {
    return {
      option: tableOption,
      dialogFormVisible: false,
      activeNames: ["1", "2", "3", "4"],
      dashData: {},
      form: {},
      regionOptionsP: [],
      regionOptionsC: [],
      OrganizationOptions: [],
      examinationDepartmentArr: [],
      hospitalDepartmentArr: [],
      examinationDepartmentOptions: [
        {label:'内科',value:'1'},
        {label:'外科',value:'2'},
        {label:'眼科',value:'3'},
        {label:'耳鼻喉',value:'4'},
        {label:'口腔科',value:'5'},
        {label:'妇科',value:'6'},
        {label:'影像科',value:'7'},
        {label:'心电图',value:'8'},
        {label:'超声科',value:'9'},
        {label:'检验科',value:'10'},
        {label:'生化',value:'11'},
        {label:'免疫',value:'12'},
        {label:'临检',value:'13'}
      ],
      hospitalDepartmentOptions: [
        {label:'消化内科',value:'1'},
        {label:'呼吸内科',value:'2'},
        {label:'内窥镜',value:'3'},
        {label:'普外',value:'4'},
        {label:'乳腺科',value:'5'},
        {label:'妇科',value:'6'},
        {label:'肿瘤科',value:'7'},
        {label:'其他',value:'8'}
      ],
      text: "",
      actor: "",
      count: 0,
      isText: false,
      charts: "",
      chartData: [],
      list: [],
      dataStuList: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条,
        isAsc: false//是否倒序
      },
      stuPage: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条,
        status: 2
      },
      listLoading: false,
      stuOption: {
        page:true,
        stripe:true,
        excelBtn: true,
        refreshBtn: false,
        columnBtn: false,
        align:'center',
        menu: false,
        dialogWidth:600,
        index: true,
        addBtn: false,
        labelWidth: 200,
        column:[
          {
            label:'学员名称',
            span: 24,
            prop:'name'
          },{
            label:'手机号',
            span: 24,
            prop:'phone'
          },{
            label:'性别',
            span: 24,
            type: 'radio',
            dicData: [{
              label: '男',
              value: 1
            }, {
              label: '女',
              value: 0
            }],
            prop:'sex'
          }, {
            label:'省',
            span: 24,
            prop:'province'
          },
            {
            label:'城市',
            span: 24,
            prop:'city'
          },{
            label:'技术负责单位',
            span: 24,
            prop:'provinceBaseName'
          },{
            label:'费用承担单位',
            span: 24,
            prop:'baseName'
          },
        ]
      }
    };
  },
  computed: {
    ...mapGetters(["website"])
  },
  mounted() {
    this.getData()
    this.getStuData({status: 3})
  },
  watch: {
    examinationDepartmentArr() {
      this.form.examinationDepartmentArr = this.examinationDepartmentArr
    },
    hospitalDepartmentArr() {
      this.form.hospitalDepartmentArr = this.hospitalDepartmentArr
    },
  },
  methods: {
    getData() {
      studentNum().then((res) => {
        this.dashData = res.data.data
      })
      provinceStudentNum().then((res) => {
        this.chartData = res.data.data
        this.$nextTick(function() {
          this.drawPie("main");
        });
      })
      // if (this.count < this.DATA.length - 1) {
      //   this.count++;
      // } else {
      //   this.count = 0;
      // }
      // this.isText = true;
      // this.actor = this.DATA[this.count];
    },
    getStuData(query = {}) {
      const {pageSize:limit, currentPage: page} = this.stuPage;
      fetchStuList('/admin/student/list', {
        ...query,
        limit,
        page,
      }).then(res => {
        if (res.code === 0) {
          const {
            currPage:currentPage,
            pageSize,
            totalCount:total,
            list
          } = res.data || {};
          this.dataStuList = list
          this.stuPage = {
            total,
            pageSize,
            currentPage,
          }
        }
      });
    },
    getList(page, params) {
      this.listLoading = true;
      fetchList(Object.assign({
        page: page.currentPage,
        size: page.pageSize
      }, params)).then(response => {
        this.list = response.data.data.list;
        this.page.total = response.data.data.totalPage
        this.listLoading = false;
      });
    },
    stuSizeChange(pageSize) {
      this.stuPage.pageSize = pageSize
    },
    stuCurrentChange(current) {
      this.stuPage.currentPage = current
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    currentChange(current) {
      this.page.currentPage = current
    },
    handleRefreshChange() {
      this.getList(this.page)
    },
    update(row, index, done, loading) {
      putObj(this.form).then(() => {
        this.getList(this.page);
        done();
        this.$notify.success('修改成功')
      }).catch(() => {
        loading();
      });
    },
    handleAdd(){
      this.$refs.crud.rowAdd();
    },
    handleUpdate(row, index) {
      this.$refs.crud.rowEdit(row, index);
    },
    create(row, done, loading) {
      this.form.examinationDepartment = this.examinationDepartmentArr.join(',')
      this.form.hospitalDepartment = this.hospitalDepartmentArr.join(',')
      this.form.sonographer = `${this.form.sonographer1},${this.form.sonographer2},${this.form.sonographer3}`
      this.form.endoscopist = `${this.form.endoscopist1},${this.form.endoscopist2},${this.form.endoscopist3}`
      this.form.gynecologist = `${this.form.gynecologist1},${this.form.gynecologist2},${this.form.gynecologist3}`
      this.form.radiographer = `${this.form.radiographer1},${this.form.radiographer2},${this.form.radiographer3}`
      this.form.inspectors = `${this.form.inspectors1},${this.form.inspectors2},${this.form.inspectors3}`
      addObj(this.form).then((res) => {
        if(res.data.code == 0){
          this.$notify.success('创建成功')
          this.getList(this.page);
          done();
        }else{
          loading();
          this.$notify.error(res.data.msg)
        }
      }).catch(() => {
        loading();
      });
    },
    handleOpenBefore(show, type) {
      window.boxType = type
      // 查询省事列表
      regionList().then(response => {
        this.regionOptionsP = response.data.data
      })
      deptOrganizationList().then(response => {
        this.OrganizationOptions = response.data.data;
      });
      // 若是编辑、查看回显角色名称
      if (['edit', 'views'].includes(type)) {
        this.role = []
        // for (let i = 0; i < this.form.roleList.length; i++) {
        //   this.role[i] = this.form.roleList[i].roleId;
        // }
      } else if (type === 'add') {
        // 若是添加角色列表设置为空
        this.role = []
      }
      show();
    },
    provinceChange(e){
      regionList({province: e}).then(response => {
        this.regionOptionsC = response.data.data
      })
    },
    drawPie(id) {
      this.charts = echarts.init(document.getElementById(id));
      this.charts.setOption({
        legend: {
          data: ['注册完成数', '未注册完成数']
        },
        tooltip: {
          trigger: 'axis'
        },
        color: ["#5981b7", "#cad9ef", "#00557C"],
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          top: "17%",
          containLabel: true
        },
        // 设置X轴的参数
        yAxis: [
          {
            type: "value",
            max: this.initMax(), 
            splitNumber: 5, 
            axisLabel: {
              show: true,
              interval: "auto",
              formatter: "{value}"
            },
            show: true
          }
        ],
        // 设置Y轴的参数
        xAxis: {
          type: "category",
          data: this.initDataName()
        },
        series: [
          {
            name: "注册完成数",
            type: "bar",
            stack: "总量",
            label: {
              show: false,
              formatter: "{c}"
            },
            data: this.initData("registerNum")
          },
          {
            name: "未注册完成数",
            type: "bar",
            stack: "总量",
            label: {
              show: false,
              formatter: "{c}"
            },
            data: this.initData("infoNotAddNum")
          }
        ]
      });
    },
    initDataName(){
      var nameList = []
      for (var i = 0; i < this.chartData.length; i++) {
        nameList.push(this.chartData[i].province)
      }
      return nameList
    },
    initMax(){
      let num = 0
      for (var i = 0; i < this.chartData.length; i++) {
        if(this.chartData[i].totalNum>num)
        num = this.chartData[i].totalNum
      }
      return num
    },
    initData(val){
      var serie = [];
      for (var i = 0; i < this.chartData.length; i++) {
        var num = 0
        num = this.chartData[i][val]
        var total = (parseFloat(this.chartData[i].totalNum)).toFixed(2);
        var numcount = this.Percentage(num,total)
        serie.push(num);
      }
      return serie;
    },
    Percentage(num, total) {
      return (Math.round(num / total * 10000) / 100.00);
    },
    setData() {
      let num = 0;
      let count = 0;
      let active = false;
      let timeoutstart = 5000;
      let timeoutend = 1000;
      let timespeed = 10;
      setInterval(() => {
        if (this.isText) {
          if (count == this.actor.length) {
            active = true;
          } else {
            active = false;
          }
          if (active) {
            num--;
            this.text = this.actor.substr(0, num);
            if (num == 0) {
              this.isText = false;
              setTimeout(() => {
                count = 0;
                this.getData();
              }, timeoutend);
            }
          } else {
            num++;
            this.text = this.actor.substr(0, num);
            if (num == this.actor.length) {
              this.isText = false;
              setTimeout(() => {
                this.isText = true;
                count = this.actor.length;
              }, timeoutstart);
            }
          }
        }
      }, timespeed);
    }
  }
};
</script>

<style scoped="scoped" lang="scss">
.wel-contailer {
  position: relative;
}

.banner-text {
  position: relative;
  padding: 0 20px;
  font-size: 20px;
  text-align: center;
  color: #333;
}

.banner-img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0.8;
  display: none;
}

.actor {
  height: 250px;
  overflow: hidden;
  font-size: 18px;
  color: #333;
}

.actor:after {
  content: "";
  width: 3px;
  height: 25px;
  vertical-align: -5px;
  margin-left: 5px;
  background-color: #333;
  display: inline-block;
  animation: blink 0.4s infinite alternate;
}

.typeing:after {
  animation: none;
}

@keyframes blink {
  to {
    opacity: 0;
  }
}
.dash {
  margin-top: 20px;
}
.dataCol {
  display: flex;
  justify-content: space-evenly;
  border-bottom: 1px dashed #f0f0f0;
  padding: 30px 0 40px;
  margin-bottom: 30px;
  .item {
    display: flex;
    padding: 20px 120px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba($color: #000000, $alpha: 0.05);
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    font-weight: 500;
    span {
      margin-top: 10px;
      font-size: 20px;
      color: #333;
      display: flex;
      align-items: center;
      b {
        font-weight: normal;
        font-size: 12px;
        cursor: pointer;
        margin-left: 5px;
      }
    }
  }
}
</style>
